var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
//获取应用实例
var app = getApp();
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext();
var vTimer = null;
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    cardInfo: {},
    companyMsg: {},
    submitInfo: {},
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    min: 5, //最少字数
    max: 500,

    recorderManager: null,
    innerAudioContext: null,
    playing: false,
    recordStatus: 0, //0 等待录音 1 录音中 2 录音结束 3 播放临时录音
    tempSound: null,
    maxSeconds: 60,
    showVoiceModal: false,
    soundTime: "00",

    uploadImgList: [],
    region: [],
    headImg: "",
    locationInfo: {},
    cardStyleId: 0,
    qiniuDomain: "",
    videoUrl: "",
    videoImg: "",
    labels: [],
    labName: "",
    showLabModal: false,
    customStyle: "",
    defCustStyleIco: cf.config.staticResPath + "/mobile/image/cust_card_ico.png",
    isAuthTel:false,

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var ctx = this;
    wx.hideShareMenu();

    var recorderManager = wx.getRecorderManager();
    var innerAudioContext = wx.createInnerAudioContext();
    ctx.setData({
      recorderManager: recorderManager,
      innerAudioContext: innerAudioContext,
    });
    recorderManager.onStart(ctx.soundRecordingCb);
    recorderManager.onStop(ctx.soundRecordedEndCb);
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      let companyMsg = wx.getStorageSync('companyInfo');
      ctx.setData({
        companyMsg: companyMsg
      })
    });
    ctx.getCardInfo();
    ctx.qiniuUploadToken();
  },
  //获取名片信息
  getCardInfo() {
    var ctx = this;
    let cardInfo = {
      name: "名字",
      tel: "13312345678",
      wxId: "",
      email:"",
      phone:"",//座机
      headPic: ctx.data.staticResPath + "/mobile/image/defaultlogo.png",
      introduction:"",
      address:""
    }

    ctx.setData({
      cardInfo: cardInfo,
      customStyle: "",
      uploadImgList: [],
      headImg: ctx.data.staticResPath + "/mobile/image/defaultlogo.png",
      cardStyleId: 0,
      submitInfo:{
        name: "",
        tel: "",
      }
    });
  },
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  bindStyleChange: function (e) {
    var idx = e.target.dataset.idx;
    this.setData({
      cardStyleId: idx
    });
  },
  inputs: function (e) {
    var ctx = this;
    ctx.data.submitInfo[e.currentTarget.id] = e.detail.value;
  },

  inputtextarea: function (e) {
    // 获取输入框的内容
    var value = e.detail.value;
    // 获取输入框内容的长度
    var len = parseInt(value.length);
    this.data.submitInfo[e.currentTarget.id] = value;
    //最少字数限制
    if (len <= this.data.min)
      this.setData({
        texts: "加油，够5个字可以得20积分哦"
      })
    else if (len > this.data.min)
      this.setData({
        texts: " "
      })

    //最多字数限制
    if (len > this.data.max) return;
    // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
    this.setData({
      currentWordNumber: len //当前字数  
    });
  },

  handleAddImage: function (e) {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        if (e.currentTarget.id == "uploadheadPic") {
          wx.navigateTo({
            url: `/pages/cropper/cropper?src=${tempFilePaths[0]}`,
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
          })
        } else {
          that.upload(that, tempFilePaths, e);
        }
      }
    })
  },

  upload: function (page, path, e) {
    let vm = this;
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    }),
      wx.uploadFile({
        url: cf.config.pageDomain + '/mobile/common/imgupload?cusmallToken=' + cusmallToken,
        filePath: path[0],
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data"
        },
        formData: {
          //和服务器约定的token, 一般也可以放在header中
          cusmallToken: cusmallToken,
        },
        success: function (res) {
          if (res.statusCode != 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            })
            return;
          }
          let data = JSON.parse(res.data);
          let uploadImgList = vm.data.uploadImgList;
          if (e.currentTarget.id == "uploadheadPic") {
            vm.setData({
              headImg: vm.data.userImagePath + data.fileName
            })
          } else {
            uploadImgList.push(data.fileName);
            vm.setData({
              uploadImgList: uploadImgList
            });
          }
        },
        fail: function (e) {
          console.log(e);
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
        },
        complete: function () {
          wx.hideToast(); //隐藏Toast
        }
      })
  },

  handleDelImg: function (e) {
    let vm = this;
    let idx = e.target.dataset.index;
    let imgList = vm.data.uploadImgList;
    if (e.currentTarget.id == "headPic") {
      vm.setData({
        headImg: null
      })
    } else {
      imgList.splice(idx, 1);
      vm.setData({
        uploadImgList: imgList
      })
    }
  },

  //提交数据
  submit: function () {
    var ctx = this;
    var submitInfo = ctx.data.submitInfo;
    submitInfo.cusmallToken = cusmallToken;
    if (!ctx.data.headImg) {
      wx.showToast({
        title: "头像不能为空",
        icon: "none"
      });
      return;
    }
    if (5 == ctx.data.cardStyleId && !ctx.data.customStyle) {
      wx.showToast({
        title: "请上传图片",
        icon: "none"
      });
      return;
    }
    if (!submitInfo.name) {
      wx.showToast({
        title: "姓名不能为空",
        icon: "none"
      });
      return;
    }
    if (!submitInfo.tel || 11 != submitInfo.tel.length) {
      wx.showToast({
        title: "手机号码不正确",
        icon: "none"
      });
      return;
    }
    if (0 == ctx.data.region.length){
      wx.showToast({
        title: "地区不能为空",
        icon: "none"
      });
      return;
    }
    submitInfo.region = JSON.stringify(ctx.data.region);
    submitInfo.uploadHeadImg = ctx.data.headImg;
    submitInfo.voiceUrl = ctx.data.voiceFile;
    submitInfo.voiceTime = ctx.data.soundTime;
    submitInfo.labels = JSON.stringify(ctx.data.labels);
    submitInfo.cardStyleId = ctx.data.cardStyleId;
    submitInfo.customStyle = ctx.data.customStyle;
    submitInfo.showPic = JSON.stringify(ctx.data.uploadImgList);
    
    wx.showLoading({
      title: '提交中...',
    });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/memberCardApply/add',
      method: "POST",
      data: submitInfo,
      header: { "Content-Type": "application/x-www-form-urlencoded" },
      success: function (res) {
        var data = res.data;
        wx.hideLoading();
        if (data && data.ret == 0) {
          wx.showModal({
            title: '提示',
            content: '提交成功，等待审核中！',
            showCancel: false,
            success(){
              wx.navigateBack({
                delta: 1
              });
            }
          });
        } else {
          wx.showModal({
            title: '提示',
            content: data.msg,
            showCancel: false
          })
        }
      },
      complete: function () {
        wx.hideLoading();
        
      }
    })
  },
  


  closeVoice() {
    var ctx = this;
    ctx.resetSound();
    ctx.setData({
      showVoiceModal: false,
    });
  },
  playSound(e) {
    var ctx = this;
    var idx = e.currentTarget.dataset.idx;
    if (ctx.data.playing) {
      return;
    }
    ctx.setData({
      playing: true,
    });
    ctx.data.innerAudioContext.src = ctx.data.voiceFile;
    ctx.data.innerAudioContext.onEnded(function () {
      ctx.setData({
        playing: false,
      });
    });
    ctx.data.innerAudioContext.play();
  },
  delVoice: function () {
    var ctx = this;
    wx.showModal({
      title: '删除录音',
      content: '确定执行此操作？',
      success: function (res) {
        if (res.confirm) {
          ctx.setData({
            voiceFile: ''
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  getPhoneNumberHandle(e){
    console.log(e);
    if (e.detail.iv){
      this.setData({
        isAuthTel:true
      });
      this.addSound();
    }
  },
  addSound() {
    var ctx = this;
    ctx.setData({
      showVoiceModal: true,
    });
  },
  /**
   * 录音开始
   */
  soundRecording() {
    var ctx = this;
    ctx.data.recorderManager.start();
  },
  soundRecordingCb() {
    var ctx = this;
    ctx.setData({
      recordStatus: 1,
      recordStartTime: Date.now(),
    });
    vTimer = setInterval(function () {
      var soundTime = parseInt(ctx.data.soundTime)
      if (ctx.data.maxSeconds <= ctx.data.soundTime) {// 超过最大时间停止录音
        ctx.soundRecorded();
        return;
      }
      soundTime++;
      soundTime = soundTime < 10 ? "0" + soundTime : soundTime; //加前置0
      ctx.setData({
        soundTime: soundTime
      });
    }, 1000);
  },
  /**
   * 录音结束
   */
  soundRecorded() {
    var ctx = this;
    ctx.data.recorderManager.stop();
  },
  soundRecordedEndCb(res) {
    var ctx = this;
    clearInterval(vTimer);
    const tempFilePath = res.tempFilePath;
    ctx.setData({
      recordStatus: 2,
      tempSound: tempFilePath
    });
    //ctx.data.recordStartTime 只有长按才会 赋值，如果没有值说明并没有长按，如果录音少于1秒也是不允许的
    if (!ctx.data.recordStartTime || (Date.now() - ctx.data.recordStartTime) < 1000) {
      ctx.resetSound();
    }
    ctx.setData({
      recordStartTime: null
    });
  },
  playTemSound() { //播放临时录制的声音
    var ctx = this;
    ctx.data.innerAudioContext.src = ctx.data.tempSound;
    ctx.data.innerAudioContext.play();
    var time = parseInt(ctx.data.soundTime) * 1000;
    ctx.data.innerAudioContext.onEnded(function () {
      ctx.setData({
        recordStatus: 2
      });
    });

    ctx.setData({
      recordStatus: 3,
    });
  },
  resetSound() { //重置声音
    var ctx = this;
    clearInterval(vTimer);
    ctx.data.innerAudioContext.stop();
    ctx.setData({
      recordStatus: 0,
      tempSound: null,
      soundTime: "00"
    });
  },
  saveSound() {
    var ctx = this;
    var voiceTime = ctx.data.soundTime;

    ctx.data.innerAudioContext.stop();
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    });
    wx.uploadFile({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/employee/uploadVoice?cusmallToken=' + cusmallToken,
      filePath: ctx.data.tempSound,
      name: 'voiceFile',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        //和服务器约定的token, 一般也可以放在header中
        cusmallToken: cusmallToken,
        voiceTime: voiceTime
      },
      success: function (res) {
        console.log(res);
        try {
          let data = JSON.parse(res.data);
          if (0 == data.ret) {
            let voiceUrl = data.model.voiceUrl || "";
            wx.showModal({
              title: '提示',
              content: '保存成功',
              showCancel: false
            })
            ctx.setData({
              voiceFile: voiceUrl,
              recordStatus: 0,
              soundTime: "00",
              showVoiceModal: false,
            });
          } else {
            wx.showModal({
              title: '提示',
              content: data.msg,
              showCancel: false
            })
          }
        } catch (e) {
          wx.showToast({
            title: e,
            icon: "none"
          })
        }


      },
      fail: function (e) {
        console.log(e);
        wx.showModal({
          title: '提示',
          content: '上传失败',
          showCancel: false
        })
      },
      complete: function () {
        wx.hideToast(); //隐藏Toast
      }
    });
  },

  /**
   * 录音结束
   */

  qiniuUploadToken() {//七牛上传token
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/qiniu/getUploadToken',
      data: {
        cusmallToken: cusmallToken,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && data.ret == 0) {
          ctx.setData({
            qiniuToken: data.model.token,
            qiniuDomain: data.model.domain
          })
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      complete: function () {
      }
    })
  },
  qiniuUpload(tempFilePath, cb) {
    var ctx = this;
    wx.showLoading({
      title: '上传中...',
    });
    var qiniuUrl = "https://upload.qiniup.com";
    if (0 <= cf.config.pageDomain.indexOf("api-card.jiuzheng.com")) {
      qiniuUrl = "https://upload-z2.qiniup.com";
    }
    wx.uploadFile({
      url: qiniuUrl,
      name: 'file',
      filePath: tempFilePath,
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        token: this.data.qiniuToken,
      },
      success: function (res) {
        let data = JSON.parse(res.data)
        console.log(res)
        if (data) {
          cb && cb(data);
        }
        wx.hideLoading();
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  handleImg() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        wx.navigateTo({
          url: `/pages/cropper/cropper?src=${tempFilePaths[0]}&saveKey=videoImg&scaleXY=1.66`,
        })
      }
    });
  },
  delSelfVideoImg() {
    this.setData({
      videoImg: ""
    });
  },

  addCustCardStyle() {
    let ctx = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        wx.navigateTo({
          url: `/pages/cropper/cropper?src=${tempFilePaths[0]}&saveKey=customStyle&scaleXY=1.68&relative=y`,
        })
      }
    });
  },
  delCusCardStyle() {
    this.setData({
      customStyle: ""
    });
  },
  toEditLabShow(){
    this.setData({
      labName: "",
      showLabModal: true
    });
  },
  toEditLab: function (e) {
    if (e.detail.iv) {

      this.setData({
        isAuthTel:true,
        labName: "",
        showLabModal: true
      });
    } else if (this.data.isAuthTel){
      
    }

    
  },
  modalCancel: function () {
    this.setData({
      showLabModal: false
    });
  }, 
  modalConfirm: function () {
    var ctx =this;
    if ("" == ctx.data.labName){
      wx.showToast({
        title: '标签不能为空',
        icon:"none"
      });
      return;
    }
    var labels = ctx.data.labels;
    var lab = {
      num:0,
      lab: ctx.data.labName
    };
    labels.push(lab);
    ctx.setData({
      labels: labels,
      showLabModal: false
    });
  },
  delLabel(e){
    let ctx = this;
    let idx = e.currentTarget.dataset.idx;
    var labels = ctx.data.labels;
    labels.splice(idx,1);
    ctx.setData({
      labels: labels
    });
  },
  labNameChange: function (e) {
    this.setData({
      labName: e.detail.value
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  chooseLocation: function (e) {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          "locationInfo": res
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function () {

  }
}))